package store;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import models.Board;
import models.Creature;
import models.Resource;

public class DataStore implements DataStoreInterface {
	
	@Override
	public Board[] getBoards() {
		// TODO
		return null;
	}

	@Override
	public boolean saveBoard(Board b) {
		try {
			
			String fname = b.getName() + ".board";
			
			File test = new File(fname);
			if(test.exists()){
				test.delete();
			}
			
			FileOutputStream fos = new FileOutputStream(fname); 
			ObjectOutputStream oos = new ObjectOutputStream(fos); 
			oos.writeObject(b);
			oos.flush(); 
			oos.close(); 
		
			return true;
		} catch (IOException e) {
			System.out.println("SORRY, couldn't save the board!");
			return false;
		} 
	}

	@Override
	public Creature[] getCreatures() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean storeCreature(Creature c) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Resource[] getResources() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean storeResource(Resource r) {
		// TODO Auto-generated method stub
		return false;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if(test()){
			System.out.println("Everything's workin' great!");
		}else{
			System.out.println("WE'VE GOT PROBLEMS!!!!!!!!!");
		}

	}
	
	public static boolean test(){
		boolean toReturn = true;
		
		//testing board persistence
		
		/*
		DataStore testDS = new DataStore();
		Board testBoard = new Board();
		testDS.saveBoard(testBoard);
		Board[] testBoards = testDS.getBoards();
		for(Board b : testBoards){
			if(b.equals(testBoard)){
				toReturn = true;
			}
		}
		
		*/
		
		DataStore testDS = new DataStore();
		Board testBoard = new Board();
		testDS.saveBoard(testBoard);
		Board returned = testDS.getBoard(testBoard.getName());
		if(!testBoard.equals(returned)){
			toReturn = false;
		}
		
		
		
		
		
		
		return toReturn;
	}

	@Override
	public Board getBoard(String boardName) {
		String fname = boardName + ".board";;
		try { 
			Board toReturn;
			FileInputStream fis = new FileInputStream(fname); 
			ObjectInputStream ois = new ObjectInputStream(fis); 
			toReturn = (Board) ois.readObject(); 
			ois.close(); 
			
			return toReturn;
			
		} catch(Exception e) { 
			System.out.println("SORRY, couldn't get " + fname + "!"); 
			return null;
		} 
	}

	@Override
	public Creature getCreature(String creatureName) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Resource getResource(String resourceName) {
		// TODO Auto-generated method stub
		return null;
	}

}
